package cn.molu.generator;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author 陌路
 * @apiNote 陌路代码生成器
 * @date 2024/1/17 12:21
 * @tool Created by IntelliJ IDEA
 */
@SpringBootApplication
public class MoluGeneratorApplication implements ApplicationRunner {

    @Value("${server.port}")
    private String port;

    public static void main(String[] args) {
        SpringApplication.run(MoluGeneratorApplication.class, args);
    }

    /**
     * 项目启动时执行
     */
    @Override
    public void run(ApplicationArguments args) {
        printInfo("==============项目启动成功！==============");
        printInfo("请访问地址：http://{}:{}", getHostIp(), port);
        printInfo("=======================================");
    }

    /**
     * 获取服务IP
     */
    private String getHostIp() {
        final String LOCAL_IP = "127.0.0.1";
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            String ip = localHost.getHostAddress();
            return StrUtil.isEmpty(ip) ? LOCAL_IP : ip;
        } catch (UnknownHostException ignored) {
        }
        return LOCAL_IP;
    }

    /**
     * 打印信息
     *
     * @param template 模板
     * @param args     参数
     */
    private void printInfo(String template, Object... args) {
        if (StrUtil.isNotBlank(template)) {
            if (null != args && args.length > 0) {
                System.out.printf(template.replaceAll("\\{}", "%s"), args);
                System.out.println();
            } else {
                System.out.println(template);
            }
        }
    }
}
